package main

import (
	"os"
	"time"

	"github.com/rs/zerolog"
	"gopkg.in/natefinch/lumberjack.v2"
)

func main() {
	zerolog.ErrorFieldName = "e"
	zerolog.TimeFieldFormat = "2006/01/02 15:04:05 -0700"

	// 以下代码 zerolog 内部实现了
	f, err := os.OpenFile("/Users/yangzhenyu/Desktop/gitee/Go/foundation/day13/ZerologWrite/log.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	// writers := []io.Writer{f, os.Stdout, os.Stderr}
	// var loggers []*zerolog.Logger
	// for _, w := range writers {
	// 	var o = log.Logger.Output(w)
	// 	loggers = append(loggers, &o)
	// }
	// msg := "test msg 群发"
	// for _, l := range loggers {
	// 	l.Info().Msg(msg)
	// }

	// 日志文件会不断膨胀，切割: 按时间、按大小、roll滚动，支持压缩？保留几个？第三方有很多
	ll := &lumberjack.Logger{
		Filename:   "/Users/yangzhenyu/Desktop/gitee/Go/foundation/day13/ZerologWrite/foo.log",
		MaxSize:    1,    // megabytes
		MaxBackups: 2,    // 除去当前写入的 foo.log外，历史文件有几个
		MaxAge:     1,    // days
		Compress:   true, // 是否历史文件变成压缩的文件
	} // 相当于 f
	defer ll.Close()
	writers := zerolog.MultiLevelWriter(f, os.Stdout, os.Stderr)
	loggers := zerolog.New(writers).With().Timestamp().Logger()
	// writers := []io.Writer{f, os.stdout, os.Stderr} // type LevelWriter []io.Writer 实现 Writer 方法
	// LevelWriter 实现 Writer 方法，内部就要遍历[]io.Writer 切片
	for {
		time.Sleep(time.Microsecond)
		msg := time.Now().Format("2006/01/02 15:04:05 -0700")
		loggers.Info().Msg(msg + msg + msg + msg + msg)
	}

	// out := zerolog.New(f).With().Timestamp().Logger().Output(f) // zerolog.New => logger 回调用 f.Write
	// out := log.Logger.Output(f)
	// out.Info().Msg("out info msg")
	// console := log.Logger.Output(os.Stdout)
	// console.Info().Msg("out info msg")
}
